package com.yonyou.pmclouds.filepreview.controller;

import com.yonyou.pmclouds.basecom.conf.USpaceProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.FilePreviewUtil;
import com.yonyou.pmclouds.basecom.view.DisableWrap;
import com.yonyou.pmclouds.filepreview.entity.FilePreviewAuthenticVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件预览支持接口(为文件预览平台开放)
 *
 * @author yzx
 * @Date: 2018/6/26 14:45
 */
@RestController
@RequestMapping("/rest/filePreview")
public class FilePreviewAuthenticController {
    @Autowired
    private USpaceProperties uspaceProperties;

    @DisableWrap
    @RequestMapping("/authentic")
    public FilePreviewAuthenticVO authenticFilePreview(HttpServletRequest request) {
        String effectStartTime = request.getParameter(FilePreviewUtil.EFFECT_START_TIME);
        if (StringUtils.isEmpty(effectStartTime)) {
            effectStartTime = "0";
        }
        long expires = Integer.valueOf(uspaceProperties.getExpires()) * 1000;
        long startTime = Long.valueOf(effectStartTime);
        // 返回内容
        FilePreviewAuthenticVO authenticVO = new FilePreviewAuthenticVO();
        Map<String, String> data = new HashMap<>();
        if (System.currentTimeMillis() - startTime <= expires) {
            // 未超时可以正常预览
            authenticVO.setCode(0);
            authenticVO.setMsg("成功!");
            data.put("view", "1");
        } else {
            // 超时不可以预览
            authenticVO.setCode(1);
            authenticVO.setLevel(1);
            authenticVO.setMsg("预览链接已经超时,请从系统中预览!");
            data.put("view", "0");
        }
        authenticVO.setData(data);
        return authenticVO;
    }
    /**
     * 公有云做一次请求的转发，保证预览只通过公有云访问友空间
     * @author:      yzx
     * @param:       fileRulePath,fileContentLength
     * @date:        2018/10/28 13:37
     */
    @DisableWrap
    @RequestMapping("/forwardPreview")
    public Object forwardPreview(@RequestParam String fileRulePath, @RequestParam long fileContentLength) throws BusinessException {
        FilePreviewUtil previewUtil = new FilePreviewUtil(uspaceProperties);
        return previewUtil.sendRequest(fileRulePath, fileContentLength);
    }
}
